import store from '@/store'

function authPermission(permission) {
  const all_permission = "*";
  const permissions = store.getters && store.getters.roles
  if (permission && permission.length > 0) {
    return permissions.some(perm => {
      if (perm === all_permission) {
        return true
      }
      const perm_str = perm.split(':')
      const permission_str = permission.split(':')
      for (let j = 0; j < permission_str.length; j++) {
        if (permission_str[j] === '*') {
          return true
        } else if (permission_str[j] !== perm_str[j]) {
          break
        }
      }
      return false
    })
  } else {
    return false
  }
}

export default {
  // 验证用户是否具备某权限
  hasPermission(permission) {
    return authPermission(permission)
  },
  // 验证用户是否含有指定权限，只需包含其中一个
  hasPermissionOr(permissions) {
    return permissions.some(item => {
      return authPermission(item)
    })
  },
  // 验证用户是否含有指定权限，必须全部拥有
  hasPermissionAnd(permissions) {
    return permissions.every(item => {
      return authPermission(item)
    })
  }
}
